package com.settlement.system.common.util;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NumberUtils {

    private static final Logger logger = LoggerFactory.getLogger(NumberUtils.class);

    public static BigDecimal convert(String text){
        try{
            text = text.replaceAll("元", "").replaceAll("null", "").strip();
            return convertBigDecimal(text);
        }catch (Exception e){
            logger.error("数字【%s】转换错误：【%s】".formatted(text, e.getMessage()));
        }
        return BigDecimal.ZERO;
    }

    public static Integer convertInteger(String text){
        try{
            return convertBigDecimal(text.strip()).intValue();
        }catch (Exception e){
            logger.error("数字【%s】转换错误：【%s】".formatted(text, e.getMessage()));
        }
        return 0;
    }

    /**
     * 转换字符串为BigDecimal
     *
     * @param money 金额字符串
     * @return 金额
     */
    public static BigDecimal convertBigDecimal(String money) {
        BigDecimal result = BigDecimal.ZERO;
        try {
            if (StrUtil.isNotEmpty(money.strip())) {
                money = money.replaceAll("，", ",").replaceAll(",", "").replaceAll(" ", "").strip();
                Pattern pattern = Pattern.compile("([+-]?\\d+\\.\\d+)");
                Matcher matcher = pattern.matcher(money);
                if (matcher.find()) {
                    result = new BigDecimal(matcher.group(0));
                } else {
                    pattern = Pattern.compile("([+-]?\\d+)");
                    matcher = pattern.matcher(money);
                    if (matcher.find()) {
                        result = new BigDecimal(matcher.group(0));
                    }
                }
            }
            return result;
        } catch (Exception e) {
            logger.error("数字【%s】转换错误：【%s】".formatted(money, e.getMessage()));
            return result;
        }
    }
}
